//引入身份凭证插件
const { json } = require("express")
const jwt = require("jsonwebtoken")

//引入已考试数据库模块
const TestedsModel_DB = require("../models/TestedsModel_DB")
//引入试卷数据库模块
const TestsModel_DB = require("../models/TestsModel_DB")
//引入发送前端工具
const Response = require("../utils/ResponseEntity")
//引入错题模块
const ErrorsModel_DB = require("../models/ErrorsModel_DB")
const { populate } = require("../models/TestedsModel_DB")

class TestedsController {
    //获取所有类型
    async findAll(req, res, next) {
        try {
            const data = await TestedsModel_DB.find()
            if (data.length) res.send(Response.success({ msg: "查询成功", data }))
            else res.send(Response.error({ msg: "查询失败" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //获取当前用户所有已考试卷
    async findByStuId(req, res, next) {
        try {
            const token = req.get("Authorization")
            const { name } = jwt.verify(token.split(" ")[1], "zheshimiyao")
            const data = await TestedsModel_DB.find()
                .populate("studentId")
                .populate({ path: "testId", populate: "pointId" })
                .populate("typeId")
            if (data.length) {
                const result = data.filter(item => item.studentId.name == name)
                res.send(Response.success({ data: result }))
            } else res.send(Response.error({ msg: "查询失败" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //接收学生考试数据
    async getStuTest(req, res, next) {
        try {
            let data = req.body
            //转换answers的json格式
            data.answers = JSON.parse(data.answers)
            if (data.studentId) {
                //根据试卷id找到对应的题目
                const { exercises } = await TestsModel_DB.findOne({ _id: data.testId }).populate("exercises").select("exercises")
                console.log(exercises);
                //对比学生答案
                let tempArr = []
                for (let i = 0; i < data.answers.length; i++) {
                    if (data.answers[i] == exercises[i].answer[0]) tempArr.push(true)
                    else tempArr.push(false)
                }
                //对比完成后，把错题id放入错题集合
                let num = 0//正确答案个数
                tempArr.forEach((item, index) => {
                    if (item == true) num++
                    else {
                        //答案错误，错题id保存到错题集合
                        ErrorsModel_DB.create({
                            studentId: data.studentId,  //学生id
                            exerciseId: exercises[index]._id,  //错题id
                            errorAnswer: [data.answers[index]]  //错误答案
                        })
                    }
                })
                data.accuracy = parseInt(num / exercises.length * 100)  //正确率
                data.score = (num / exercises.length * 100).toFixed(2)  //分数
                //把试卷存入已考试卷
                const { _id } = await TestedsModel_DB.create(data)
                //添加成功给前端发送已考试卷id
                if (_id) res.send(Response.success({ data: _id }))
                else res.send(Response.error({ msg: "添加失败" }))
            } else res.send(Response.error({ msg: "数据传输不正确" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //根据id查询数据
    async findById(req, res, next) {
        try {
            const { id } = req.query
            const data = await TestedsModel_DB.findOne({ _id: id }).populate({
                path: "testId",
                populate: [{ path: "exercises" }]
            })
            if (data._id) res.send(Response.success({ data }))
            else res.send(Response.error({ msg: "查询失败" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }
}

const testeds = new TestedsController()
module.exports = testeds